// 数据库连接
// const { json } = require('body-parser');
// const { body } = require('express-validator');
// 导入邮件发送模块
const sendMail = require('../util/email')
const {
    sequelize
} = require('../model/db');
const { DataTypes } = require('sequelize')
// user数据模型
const { User } = require('../model/user');
// 导入邮箱验证码模型
const { EmailCode } = require('../model/emailCode')
// 导入jwt
const jwt = require('../util/jwt')
// 导入密钥
const { uuid } = require('../config/config.default');
const { verify } = require('crypto');

// controller 用于操作数据库和返回结果给服务器
/**
 * 用户登录
 */
exports.login = async (req, res, next) => {
    const username = req.body.user.username
    try {
        const token = await jwt.sign({
            user: req.body.user
        }, uuid, {
            // 设置token过期时间
            expiresIn: 60 * 60 * 24
        })
        res.status('200').json({
            username, token
        },)
        console.log('用户登录成功')
    } catch (err) {
        next(err)
    }
}
/**
 * 用户注册
 */
exports.registeUser = async (req, res, next) => {
    try {
        // 1.获取请求体数据
        console.log(req.body.user)
        // 2.数据验证
        // 2.1 基本数据验证

        // 2.2 业务数据验证
        console.log(req.body.user)
        // 3.验证通过，将数据保存到数据库
        // User.create 将数据保存到user中
        const user = await User.create(req.body.user);
        let registerUser_account = user.username;
        let registerUser_status = user instanceof User;
        console.log(`注册账号：${registerUser_account} 状态：${registerUser_status}`, registerUser_account, registerUser_status);
        // 4.发送请求成功响应
        res.status(201).json(user);
        // console.log()
    } catch (err) {
        next(err)
    }
}

/**
 * 给用户发送邮箱验证码
 */
exports.emailCode = async (req, res, next) => {
    try {
        console.log(req.body.user)
        // 生成4位随机验证码
        let code = Math.random().toString().slice(-4);

        // //发送验证码邮件 
        let email_info = `<!doctype html><html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office"><head><title></title><!--[if !mso]><!--><meta http-equiv="X-UA-Compatible" content="IE=edge"><!--<![endif]--><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"><style type="text/css">#outlook a { padding:0; }
        body { margin:0;padding:0;-webkit-text-size-adjust:100%;-ms-text-size-adjust:100%; }
        table, td { border-collapse:collapse;mso-table-lspace:0pt;mso-table-rspace:0pt; }
        img { border:0;height:auto;line-height:100%; outline:none;text-decoration:none;-ms-interpolation-mode:bicubic; }
        p { display:block;margin:13px 0; }</style><!--[if mso]>
      <noscript>
      <xml>
      <o:OfficeDocumentSettings>
        <o:AllowPNG/>
        <o:PixelsPerInch>96</o:PixelsPerInch>
      </o:OfficeDocumentSettings>
      </xml>
      </noscript>
      <![endif]--><!--[if lte mso 11]>
      <style type="text/css">
        .mj-outlook-group-fix { width:100% !important; }
      </style>
      <![endif]--><style type="text/css">@media only screen and (min-width:480px) {
      .mj-column-per-100 { width:100% !important; max-width: 100%; }
    }</style><style media="screen and (min-width:480px)">.moz-text-html .mj-column-per-100 { width:100% !important; max-width: 100%; }</style><style type="text/css"></style></head><body style="word-spacing:normal;"><div><!--[if mso | IE]><table align="center" border="0" cellpadding="0" cellspacing="0" class="" style="width:600px;" width="600" ><tr><td style="line-height:0px;font-size:0px;mso-line-height-rule:exactly;"><![endif]--><div style="margin:0px auto;max-width:600px;"><table align="center" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width:100%;"><tbody><tr><td style="direction:ltr;font-size:0px;padding:20px 0;text-align:center;"><!--[if mso | IE]><table role="presentation" border="0" cellpadding="0" cellspacing="0"><tr><td class="" style="vertical-align:top;width:600px;" ><![endif]--><div class="mj-column-per-100 mj-outlook-group-fix" style="font-size:0px;text-align:left;direction:ltr;display:inline-block;vertical-align:top;width:100%;"><table border="0" cellpadding="0" cellspacing="0" role="presentation" style="vertical-align:top;" width="100%"><tbody><tr><td align="center" style="font-size:0px;padding:10px 25px;word-break:break-word;"><div style="font-family:helvetica;font-size:20px;line-height:1;text-align:center;color:#F45E43;">萌宠乐园</div></td></tr><tr><td align="center" style="font-size:0px;padding:10px 25px;word-break:break-word;"><p style="border-top:solid 4px #F45E43;font-size:1px;margin:0px auto;width:100%;"></p><!--[if mso | IE]><table align="center" border="0" cellpadding="0" cellspacing="0" style="border-top:solid 4px #F45E43;font-size:1px;margin:0px auto;width:550px;" role="presentation" width="550px" ><tr><td style="height:0;line-height:0;"> &nbsp;
</td></tr></table><![endif]--></td></tr><tr><td align="left" style="font-size:0px;padding:10px 25px;word-break:break-word;"><div style="font-family:helvetica;font-size:20px;line-height:1;text-align:left;color:#F45E43;">您好：</div></td></tr><tr><td align="left" style="font-size:0px;padding:10px 25px;word-break:break-word;"><div style="font-family:helvetica;font-size:20px;line-height:1;text-align:left;color:#F45E43;">我们收到了您重置验证码的请求，您的验证码是：</div></td></tr><tr><td align="center" style="font-size:0px;padding:10px 25px;word-break:break-word;"><div style="font-family:helvetica;font-size:26px;line-height:1;text-align:center;color:#F45E43;">${code}</div></td></tr><tr><td align="left" style="font-size:0px;padding:10px 25px;word-break:break-word;"><div style="font-family:helvetica;font-size:20px;line-height:1;text-align:left;color:#F45E43;">该验证码5分钟内有效。请不要把验证码泄露给其他人。如非本人操作，请忽略本邮件。</div></td></tr></tbody></table></div><!--[if mso | IE]></td></tr></table><![endif]--></td></tr></tbody></table></div><!--[if mso | IE]></td></tr></table><![endif]--></div></body></html>`
        // 发送邮件
        sendMail(req.body.user.email, '找回密码', email_info, function (err, res) {
            console.log(err);
        });

        // 将验证码存入数据库
        const emailCode = await EmailCode.create({
            username: req.body.user.username,
            email: req.body.user.email,
            emailCode: code,
            // 获取当前时间戳
            timestamp: Date.now()
        })
        console.log(emailCode instanceof EmailCode);
        res.status(200).json({ 'msg': '验证码发送成功' })

    } catch (err) {
        next(err)
    }
}
/**
 * 验证邮箱验证码
 */
exports.verifyEmailCode = async (req, res, next) => {
    console.log(req.body.user)
    // res.send(200, 'ok');
    try {
        const emailCode = await EmailCode.findOne({
            where: {
                emailCode: req.body.user.emailCode
            }
        })
        // 获取当前时间戳
        let timestamp = Date.now();
        // 获取验证码时间戳
        let emailCode_timestamp = emailCode.timestamp;
        // 判断验证码是否过期
        if (timestamp - emailCode_timestamp > 50000000) {
            res.status(200).json({ 'msg': '验证码已过期，请重新获取' })
        } else {
            // 删除数据库中的验证码记录
            const emailCode = await EmailCode.destroy({
                where: {
                    email: req.body.user.email
                }
            })
            // // 更新数据库中的密码
            const user = await User.update({
                password: req.body.user.password
            }, {
                where: {
                    email: req.body.user.email
                }
            })
            res.status(200).json({ 'msg': '密码修改成功' })
        }
    } catch (err) {
        next(err)
    }
}
/**
 * 获取当前登录用户
 */
exports.getCurrentUser = async (req, res, next) => {
    try {
        res.status(200).json({
            username: req.user
        })
    } catch (err) {
        next(err)
    }
}
/**
 * 更新当前登录用户
 */
exports.updateCurrentUser = async (req, res, next) => {
    try {
        res.send(200, 'ok')
        console.log(res.body)
    } catch (err) {
        next(err)
    }
}
